package com.glory.dgcpcpda.activity.cpc;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;

import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;
import com.glory.dgcpcpda.R;
import com.glory.dgcpcpda.activity.mfg.ShiftExchangeTestActivity;
import com.glory.dgcpcpda.base.BaseActivity;
import com.glory.dgcpcpda.base.Constant;
import com.glory.dgcpcpda.callback.CustomDialogEntityCallBack;
import com.glory.dgcpcpda.callback.RequestCallBack;
import com.glory.dgcpcpda.entity.AdrefListEntity;
import com.glory.dgcpcpda.entity.EqpInfoEntity;
import com.glory.dgcpcpda.entity.LotInfoEntity;
import com.glory.dgcpcpda.entity.ProgramEqpInfoEntity;
import com.glory.dgcpcpda.entity.response.BaseResponseBean;
import com.glory.dgcpcpda.utils.LotUtils;
import com.glory.dgcpcpda.utils.NetUtils;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_EditTextUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class UploadPictureActivity extends BaseActivity {
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.etEqpWork)
    FreeUI_ClearEditText etEqpWork;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.flPictureDescriptionList)
    FrameLayout flPictureDescriptionList;
    @BindView(R.id.ivPictureDescription)
    ImageView ivPictureDescription;
    @BindView(R.id.etPictureDescription)
    TextView etPictureDescription;
    @BindView(R.id.tvLocation)
    TextView tvLocation;

    private List<String> selectList = new ArrayList<>();
    private FreeUI_GeneralPop mSelectList;
    private String mSelect = "";
    private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1;
    private String currentPhotoPath;
    private File cameraSavePath;//拍照照片路径
    private Uri uri;//照片uri
    private String photoPath;
    private String body = "";
    private  List<AdrefListEntity.Adref> adreflist = new ArrayList<>() ;
    private  List<AdrefListEntity.Adref> adreflist2 = new ArrayList<>() ;


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_cpc_uploadpicture;
    }

    @Override
    protected void initView() {
        tvTitle.setText("拍照上传");
        setMainLayout(llMain);
        tvBaseSubmit.setVisibility(View.VISIBLE);
        tvBaseSubmit.setText("拍照");

        initEdit(etEqpWork, s -> {
            LotUtils.searchEqpInfo(s, UploadPictureActivity.this, getSupportFragmentManager(), new LotUtils.netCallback<EqpInfoEntity>() {
                @Override
                public void onSuccess(EqpInfoEntity response) {
                    tvLocation.setText(response.getEQUIPMENT().getLOCATION());
                    showCarrierLayout(response);
                }

                @Override
                public void onFail(Throwable t) {
                    loadError(t, "EQPQUERY");
                }
            });
        });

        initEdit(etLot, s -> {
            LotUtils.searchLotInfo(UploadPictureActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
                @Override
                public void onSuccess(LotInfoEntity response) {
                }

                @Override
                public void onFail(Throwable t) {
                    loadError(t,"LOTQUERY");
                }
            });
        });

    }

    //获取MES动态栏位参考值
    private void showCarrierLayout(EqpInfoEntity data) {
        FreeUI_EntityCallBack<BaseResponseBean<AdrefListEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<AdrefListEntity>>
                (new TypeToken<BaseResponseBean<AdrefListEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onSuccess(Response<BaseResponseBean<AdrefListEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())){
                    adreflist = response.body().getResponse().getBody().getADREFLIST();
                    selectList.clear();
                    adreflist2.clear();
                    for(int i=0;i<adreflist.size();i++)
                    {
                        if(data.getEQUIPMENT().getDEPARTMENT().contains(adreflist.get(i).getDESCRIPTION()))
                        {
                            selectList.add(adreflist.get(i).getKEY());
                            adreflist2.add(adreflist.get(i));
                        }
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<AdrefListEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"ADREFLISTQUERY");

            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("REFERENCETYPE","USER");
        map.addProperty("REFERENCENAME","CPC_EAP_UPLOADPICTURE");
        NetUtils.requestPostNet("CPC.ADREFLISTQUERY","ADREFLISTQUERY",this,map,callBack);
    }

    @Override
    protected void initData() {
    }

    @OnClick({R.id.flPictureDescriptionList,R.id.tvBaseSubmit})
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.tvBaseSubmit:
                if (getText(etEqpWork).equals("")){
                    showToast("设备号不能为空",false);
                    return;
                }
                if (etPictureDescription.getText().toString().equals("")){
                    showToast("图片描述不能为空",false);
                    return;
                }

                if (tvLocation.getText().toString().equals("")){
                    showToast("设备位置号不能为空",false);
                    return;
                }
                // 调用拍照功能
                takePhoto();
                break;
            case R.id.flPictureDescriptionList:
                if (selectList.size() <= 0) {
                    showToast("未获取到列表", false);
                    return;
                }
                if (mSelectList != null) {
                    if (mSelectList.isShowing()) {
                        mSelectList.dismiss();
                    }
                } else {
                    mSelectList = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flPictureDescriptionList.getWidth(), selectList, ivPictureDescription, (codeS, i) -> {
                        etPictureDescription.setText(codeS);
                    });
                }
                FreeApi_PopUtils.setArrowShow(ivPictureDescription);
                mSelectList.showAsDropDown(flPictureDescriptionList, 0, 0);
                break;
        }



    }


    private void takePhoto() {
        cameraSavePath = new File(Environment.getExternalStorageDirectory().getPath() + "/" +"photo.jpg");
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //第二个参数为 包名.fileprovider
            uri = FileProvider.getUriForFile(UploadPictureActivity.this,
                    "com.glory.dgcpcpda.fileprovider", cameraSavePath);//这里传你应用的包名
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            uri = Uri.fromFile(cameraSavePath);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        UploadPictureActivity.this.startActivityForResult(intent, 1);
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) {
            switch (requestCode) {
                case 1:
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        photoPath = String.valueOf(cameraSavePath);
                    } else {
                        photoPath = uri.getEncodedPath();
                    }
                    requestUploadPhoto();
                    break;
            }
        }
    }

    private void requestUploadPhoto() {
        Map<String, String> pramas = new HashMap<>();
        List filemaps = new ArrayList();
        filemaps.add(photoPath);
        // 装载参数
        pramas.put("ImgType", "jpg");
        pramas.put("UserCode", Constant.CURRENT_USER);
        pramas.put("EQP_ID", etEqpWork.getText().toString());
        pramas.put("LOT_ID", etLot.getText().toString());
        pramas.put("LOCATION", tvLocation.getText().toString());
        for(int i=0;i<adreflist2.size();i++)
        {
            if(etPictureDescription.getText().toString().equals(adreflist2.get(i).getKEY())){
                pramas.put("ImgGroup",adreflist2.get(i).getTEXT());
                pramas.put("ImgGroupCh",adreflist2.get(i).getKEY());
            }
        }

        RequestCallBack<BaseResponseBean> baseResponseBeanRequestCallBack = new RequestCallBack<BaseResponseBean>(new TypeToken<BaseResponseBean<JSONObject>>() {
        }.getType()){
            @Override
            public void onFailure(Call call, IOException e) {
                super.onFailure(call, e);
            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                super.onResponse(call, response);
                showConfirmDialog(this.Body.getResponse().getHeader().getRESULTMESSAGE());
            }
        };

        NetUtils.requestCpcPhoto("UploadImage", pramas, filemaps, baseResponseBeanRequestCallBack);
    }

    protected void initEdit2(EditText editText, final editTextListener listener){
        editText.setImeOptions(EditorInfo.IME_ACTION_GO);
        editText.setSingleLine(true);
        editText.setOnEditorActionListener((textView, i, keyEvent) -> {
            if (EditorInfo.IME_ACTION_GO == i) {
                String text = editText.getText().toString();
                editText.getText().clear();
                editText.setText(text);
                editText.setSelection(editText.getText().length());
                return true;
            }
            return false;
        });
        FreeApi_EditTextUtils.setEditTextListener(editText, this, s -> {
            if (listener != null){
                listener.onTextChangeListener(s);
            }
        });
    }

}
